package zb.wzby;

import java.sql.SQLSyntaxErrorException;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @author wzby
 * @Date: 2022/8/10 11:22
 */
public class Parking {
    Semaphore se = new Semaphore(3);
    //定义semaphore实例
    void stop(){
        String str = Thread.currentThread().getName();
        try {
            System.out.printf("%s准备停车%n", str);
            se.acquire();
            //尝试获取许可，如果没有，则等待
            long time = (long) (Math.random() * 50 + 10);
            System.out.printf("%s进入停车场，停车%d分钟%n",str,time);
            TimeUnit.SECONDS.sleep(time);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            System.out.printf("%s准备驶离停车场%n",str);
            se.release();
            //释放许可
            System.out.printf("%s离开停车场%n",str);
        }
    }

    public static void main(String[] args) {
        Parking s = new Parking();
        new Thread(s::stop,"豫A4312").start();
        new Thread(s::stop,"豫E4312").start();
        new Thread(s::stop,"豫G4312").start();
        new Thread(s::stop,"豫B4312").start();
        new Thread(s::stop,"豫U4312").start();
        new Thread(s::stop,"豫P4312").start();
    }
}
